# ===== Makefile.ios =====

FLUTTER := flutter
APP_NAME := Runner

DEVICE_IDS := $(shell flutter devices --machine | jq -r '.[] | select(.targetPlatform == "ios") | .id')


ARCHIVE_PATH := build/ios/archive/$(APP_NAME).xcarchive
EXPORT_PATH := build/ios/ipa
EXPORT_OPTIONS := ios/exportOptions.plist
IPA_FILE := $(EXPORT_PATH)/$(APP_NAME).ipa

APPLE_ID := your@appleid.com
APP_SPECIFIC_PASSWORD := app-specific-password-here

.PHONY: ios ios-run ios-archive ios-ipa ios-upload pod-install pod-deintegrate ios-clean

ios:
	$(FLUTTER) build ios --release

ios-run:
	@for DEVICE in $(DEVICE_IDS); do \
		echo "Trying device $$DEVICE..."; \
		if $(FLUTTER) run -d $$DEVICE; then \
			exit 0; \
		fi; \
	done; \
	echo "No available devices succeeded."; \
	exit 1

ios-archive: ios-clean
	$(FLUTTER) build ios --release
	xcodebuild archive \
		-workspace ios/Runner.xcworkspace \
		-scheme Runner \
		-configuration Release \
		-sdk iphoneos \
		-archivePath $(ARCHIVE_PATH) \
		CODE_SIGN_STYLE=Manual

ios-ipa: ios-clean ios-archive
	xcodebuild -exportArchive \
		-archivePath $(ARCHIVE_PATH) \
		-exportOptionsPlist $(EXPORT_OPTIONS) \
		-exportPath $(EXPORT_PATH)

ios-upload: ios-ipa
	xcrun altool --upload-app \
		-f $(IPA_FILE) \
		-t ios \
		-u "$(APPLE_ID)" \
		-p "$(APP_SPECIFIC_PASSWORD)"

pod-install:
	@echo "--> [iOS] Running 'pod install' in the ios directory..."
	@cd ios && pod install && cd ..

pod-deintegrate:
	@echo "--> [iOS] Running 'pod install' in the ios directory..."
	@cd ios && pod-deintegrate && cd ..

ios-clean:
	@echo "清理 Flutter iOS 构建缓存和 Xcode DerivedData..."
	rm -rf ios/Flutter/ephemeral
	# 删除 Flutter ios build 目录
	rm -rf build/ios
	# 删除 archive 产物
	rm -rf build/ios/archive
	rm -rf build/ios/ipa
	# 删除 Xcode DerivedData 对应项目缓存（注意替换PROJECT_NAME）
	rm -rf $(DERIVED_DATA_DIR)/$(PROJECT_NAME)-*
	@echo "清理完成."

